package com.czk.springcloud.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.UUID;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/18 14:59
 */
@Order(-1)
@Component
public class AddHeaderFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != attributes) {
            // 拿到request
            HttpServletRequest request = attributes.getRequest();
            // 拿到所有的header
            Enumeration<String> headerNames = request.getHeaderNames();
            // 遍历
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                requestTemplate.header(headerName, request.getHeader(headerName));
            }
            // 微服务之间传递的唯一标识,区分大小写所以通过httpServletRequest获取
            if (request.getHeader("czk") == null) {
                requestTemplate.header("czk", UUID.randomUUID().toString().replaceAll("-", ""));
            }
        }
    }
}
